﻿#include "WRProcQueue.h"

#include <QRunnable>
#include <QThreadPool>
#include <QMutexLocker>

//初始化当前对象。
WRProcQueue::WRProcQueue(void)
{
    m_status = false;
    setAutoDelete(false);
}
//清理当前对象所占用的相关资源。
WRProcQueue::~WRProcQueue(void)
{
    //要求所有的处理项目执行完成。
    while(m_queue.count())
    {
        QThread::yieldCurrentThread();
    }
    do
    {
        bool status = true;
        m_mutex.lock();
        status = m_status;
        m_mutex.unlock();
        if (!status)
        {
            QThread::yieldCurrentThread();
        }
        else
        {
            break;
        }
    }while(true);
}

//线程池方法调用。
void WRProcQueue::run()
{
    WRProcEntry* entry;

    m_mutex.lock();
    if (m_queue.count())
    {
        entry = m_queue.dequeue();
    }
    else
    {
        m_status = false;
        m_mutex.unlock();
        return;
    }
    m_mutex.unlock();

    entry->process();
    entry->release();

    m_mutex.lock();
    if (m_queue.count())
    {
        QThreadPool* threadPool = QThreadPool::globalInstance();
        threadPool->start(this);
    }
    else
    {
        m_status = false;
    }
    m_mutex.unlock();
}

//取消队列中的所有项目的处理。
void WRProcQueue::discard(void)
{
    QMutexLocker locker(&m_mutex);
    while(m_queue.count())
    {
        WRProcEntry* entry = m_queue.dequeue();
        entry->discard();
        entry->release();
    }
}
//将处理项目添加到队列中以进行处理。
void WRProcQueue::process(WRProcEntry* entry)
{
    entry->addRef();
    QMutexLocker locker(&m_mutex);
    m_queue.enqueue(entry);
    if (!m_status)
    {
        m_status = true;
        QThreadPool* threadPool = QThreadPool::globalInstance();
        threadPool->start(this);
    }
}
